# 1.epoll并不代表一定比select好
# 在并发高的情况下，连接活跃度不是很高，epoll比select
# 并发性不高，同时连接很活跃，select比epoll好

import socket
from urllib.parse import urlparse

# 使用非阻塞io完成http请求

def get_url(url):
    # 通过socket请求html
    url = urlparse(url)
    # 获得域名
    host = url.netloc
    # 获得资源路径
    path = url.path
    if path == "":
        path = "/"

    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.setblocking(False)

    try:
        client.connect((host, 80))
    except BlockingIOError as e:
        pass

    while True:
        try:
            client.send("GET {} HTTP/1.1\r\nHost:{}\r\nConnection:close\r\n\r\n".format(path,host).encode("utf8"))
            break
        except OSError as e:
            pass
    data = b""
    while True:
        try:
            temp = client.recv(1024)
        except BlockingIOError as e:
            continue

        if temp:
            data += temp
        else:
            break
    data = data.decode("utf8")
    html_data = data.split("\r\n\r\n")[1]
    # print(data)
    print(html_data)
    client.close()

if __name__ == '__main__':
    get_url("http://www.baidu.com")




